<!--
  * 数据字典表
  *
  * @Author:    zzb
  * @Date:      2025-01-23 04:08:26
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="字典名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="dataQueryForm.nameLeftLike" placeholder="字典名称" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <div class="main-container">
    <div class="dict-container">
      <div class="dict-parent">
        <div class="dict-header">
          <span class="title">字典父码表</span>
          <a-button @click="showDataForm(undefined)" type="primary">
            <template #icon>
              <PlusOutlined />
            </template>
            添加
          </a-button>
        </div>

        <a-table
          class="dict-table"
          size="small"
          :dataSource="dataTableData"
          :columns="dataColumns"
          rowKey="id"
          :loading="dataTableLoading"
          :row-class-name="(_record, index) => (_record.id === selectedDictId.value ? 'ant-table-row-selected' : '')"
          :pagination="{
            total: dataTotal,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }"
          @change="handleTableChange"
          @showSizeChange="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'action'">
              <a-button type="link" @click="showDataForm(record)">编辑</a-button>
              <a-button type="link" danger @click="onDeleteData(record)">删除</a-button>
            </template>
          </template>
        </a-table>

        <DataDictionariesForm ref="dataFormRef" @reloadList="queryData" />
      </div>

      <div class="dict-sub">
        <div class="dict-header">
          <span class="title">字典子码表</span>
          <a-button @click="showDataSubForm(undefined)" type="primary">
            <template #icon>
              <PlusOutlined />
            </template>
            添加
          </a-button>
        </div>

        <a-table
          size="small"
          :dataSource="dataSubTableData"
          :columns="dataSubColumns"
          rowKey="id"
          :loading="dataSubTableLoading"
          :pagination="{
            total: dataSubTotal,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共${total}条`,
          }"
          @change="handleSubTableChange"
          @showSizeChange="handleSubTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'status'">
              <a-switch :loading="loading" :checked="record.status" :checked-value="1" :unchecked-value="0" @change="handleStatusChange(record)" />
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button type="link" @click="showDataSubForm(record)">编辑</a-button>
              <a-button type="link" danger @click="onDeleteSubData(record)">删除</a-button>
            </template>
          </template>
        </a-table>

        <DataSubDictionariesForm ref="dataSubformRef" @reloadList="querySubData" />
      </div>
    </div>
  </div>
</template>
<script setup>
  import { reactive, ref, onMounted, h, resolveComponent, computed } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { dataSubDictionariesApi } from '/src/api/business/b-operation/data-dictionaries/data-sub-dictionaries-api'
  import { dataDictionariesApi } from '/src/api/business/b-operation/data-dictionaries/data-dictionaries-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import DataDictionariesForm from './data-dictionary-form.vue'
  import DataSubDictionariesForm from './data-sub-dictionary-form.vue'
  import { SoundTwoTone } from '@ant-design/icons-vue'
  //import FilePreview from '/@/components/support/file-preview/role-user-list.vue'; // 图片预览组件

  // ---------------------------- 表格列 ----------------------------

  const dataColumns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      customRender: ({ index }) => {
        return (dataQueryForm.pageNo - 1) * dataQueryForm.pageSize + index + 1
      },
    },
    {
      title: '字典名称',
      dataIndex: 'name',
      ellipsis: true,
      customRender: ({ text, record }) => {
        return h(
          'a',
          {
            onClick: () => handleDictClick(record),
            style: {
              color: record.id === selectedDictId.value ? 'red' : '#1890ff', // 点击后变为红色
              cursor: 'pointer',
              textDecoration: record.id === selectedDictId.value ? 'underline' : 'none', // 添加下划线
            },
          },
          text,
        )
      },
    },
    {
      title: '字典编码',
      dataIndex: 'code',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 140,
    },
  ])
  const dataSubColumns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      customRender: ({ index }) => {
        return (dataSubQueryForm.pageNo - 1) * dataSubQueryForm.pageSize + index + 1
      },
    },
    {
      title: '字典项名称',
      dataIndex: 'itemName',
      ellipsis: true,
    },
    {
      title: '字典值',
      dataIndex: 'value',
      ellipsis: true,
    },
    {
      title: '排序',
      dataIndex: 'num',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 140,
    },
  ])
  // ---------------------------- 查询数据表单和方法 ----------------------------

  const dataQueryFormState = {
    nameLeftLike: undefined, //字典名称
    pageNo: 1,
    pageSize: 10,
  }
  const dataSubQueryFormState = {
    dictId: undefined,
    sortFields: [
      {
        field: 'num',
        order: 'asc',
      },
    ],
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const dataQueryForm = reactive({ ...dataQueryFormState })
  const dataSubQueryForm = reactive({ ...dataSubQueryFormState })
  // 表格加载loading
  const dataTableLoading = ref(false)
  const dataSubTableLoading = ref(false)
  // 表格数据
  const dataTableData = ref([])
  const dataSubTableData = ref([])
  // 总数
  const dataTotal = ref(0)
  const dataSubTotal = ref(0)

  const handleTableChange = (pagination) => {
    dataQueryForm.pageNo = pagination.current
    dataQueryForm.pageSize = pagination.pageSize
    queryData()
  }
  const handleSubTableChange = (pagination) => {
    dataSubQueryForm.pageNo = pagination.current
    dataSubQueryForm.pageSize = pagination.pageSize
    querySubData()
  }

  // 重置查询条件
  function resetQuery() {
    let pageSize = dataQueryForm.pageSize
    Object.assign(dataQueryForm, dataQueryFormState)
    dataQueryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    dataQueryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  function queryData() {
    dataTableLoading.value = true
    try {
      dataDictionariesApi.queryPage(dataQueryForm).then((res) => {
        const data = res.data
        dataTableData.value = data
        dataTotal.value = res?.total

        // 如果有数据且没有选中的行，自动选中第一条
        if (dataTableData.value?.length > 0 && !selectedDictId.value) {
          handleDictClick(dataTableData.value[0])
        }
      })
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      dataTableLoading.value = false
    }
  }

  function querySubData() {
    dataSubTableLoading.value = true
    try {
      dataSubDictionariesApi.queryPage(dataSubQueryForm).then((res) => {
        const data = res.data
        dataSubTableData.value = data
        dataSubTotal.value = res?.total
      })
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      dataSubTableLoading.value = false
    }
  }

  // 添加状态切换处理函数
  async function handleStatusChange(record) {
    try {
      SmartLoading.show()
      const param = {
        id: record.id,
        status: record.status === 0 ? 1 : 0, // 根据当前状态设置新的状态值
      }

      await dataSubDictionariesApi.updateStatus(param) // 调用后端接口更新状态
      message.success('状态更新成功') // 提示用户更新成功
      await querySubData() // 重新查询数据以确保数据一致性
    } catch (e) {
      smartSentry.captureError(e) // 捕获错误并上报
      message.error('状态更新失败') // 提示用户更新失败
      record.status = !record.status // 回滚状态
    } finally {
      SmartLoading.hide() // 隐藏加载动画
    }
  }

  onMounted(queryData)

  // ---------------------------- 添加/修改/删除 ----------------------------
  const dataFormRef = ref()
  const dataSubformRef = ref()

  async function showDataForm(data) {
    try {
      SmartLoading.show()
      // 如果 data 是 undefined，表示新增，不需要查询
      if (data) {
        const param = {
          id: data.id,
        }
        const queryResult = await dataDictionariesApi.findOne(param)
        data = queryResult.data // 使用后端返回的最新数据
      }
      dataFormRef.value.show(data)
    } catch (e) {
      smartSentry.captureError(e)
      message.error('获取数据失败')
    } finally {
      SmartLoading.hide()
    }
  }
  async function showDataSubForm(data) {
    try {
      SmartLoading.show()
      const selectedDict = dataTableData.value.find((item) => item.id === selectedDictId.value)
      if (selectedDict) {
        // 如果 data 是 undefined，表示新增，不需要查询
        if (data) {
          const param = {
            id: data.id,
          }
          const queryResult = await dataSubDictionariesApi.findOne(param)
          data = queryResult.data // 使用后端返回的最新数据
        } else {
          data = {}
        }
        data.dictId = selectedDict.id
        dataSubformRef.value.show(data)
      } else {
        message.warning('请先选择一个字典项')
      }
    } catch (e) {
      smartSentry.captureError(e)
      message.error('获取数据失败')
    } finally {
      SmartLoading.hide()
    }
  }

  function onDeleteData(data) {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除字典 "${data.name}" 吗？删除后不可恢复！`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        try {
          const param = {
            id: data.id,
          }
          SmartLoading.show()
          await dataDictionariesApi.delete(param)
          message.success('删除成功')
          await queryData()
        } catch (e) {
          smartSentry.captureError(e)
          message.error('删除失败')
        } finally {
          SmartLoading.hide()
        }
      },
    })
  }
  function onDeleteSubData(data) {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除字典项 "${data.itemName}" 吗？删除后不可恢复！`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        try {
          const param = {
            id: data.id,
          }
          SmartLoading.show()
          await dataSubDictionariesApi.delete(param)
          message.success('删除成功')
          await querySubData()
        } catch (e) {
          smartSentry.captureError(e)
          message.error('删除失败')
        } finally {
          SmartLoading.hide()
        }
      },
    })
  }
  // // ---------------------------- 批量删除 ----------------------------

  // // 选择表格行
  // const selectedRowKeyList = ref([]);

  // // 批量删除
  // function confirmBatchDelete() {
  //     Modal.confirm({
  //         title: '提示',
  //         content: '确定要批量删除这些数据吗?',
  //         okText: '删除',
  //         okType: 'danger',
  //         onOk() {
  //             requestBatchDelete();
  //         },
  //         cancelText: '取消',
  //         onCancel() {},
  //     });
  // }

  // //请求批量删除
  // async function requestBatchDelete() {
  //     try {
  //         SmartLoading.show();
  //         await dataDictionariesApi.batchDelete(selectedRowKeyList.value);
  //         message.success('删除成功');
  //         queryData();
  //     } catch (e) {
  //         smartSentry.captureError(e);
  //     } finally {
  //         SmartLoading.hide();
  //     }
  // }

  // 添加点击处理函数
  function handleDictClick(record) {
    // 高亮选中的行
    selectedDictId.value = record.id
    // 更新子表查询条件
    dataSubQueryForm.dictId = record.id
    // 重置子表分页
    dataSubQueryForm.pageNo = 1

    querySubData()
  }

  // 添加选中行的状态
  const selectedDictId = ref(null)
</script>

<style lang="less" scoped>
  .main-container {
    background: #fff;
    padding: 16px;
    border-radius: 2px;
  }

  .dict-container {
    display: flex;
    gap: 24px;

    .dict-parent,
    .dict-sub {
      flex: 1;
    }

    .dict-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .title {
        font-size: 18px;
        font-weight: bold;
        color: #666666;
        line-height: 22px;
      }
    }
  }

  // 修改表格样式
  :deep(.dict-table),
  :deep(.ant-table-wrapper) {
    .ant-table {
      border-radius: 0;
      border: 1px solid #f0f0f0;
      color: #666666;
    }

    .ant-table-container {
      border-radius: 0;
    }

    .ant-table-content {
      border-radius: 0;
    }

    // 表头样式
    .ant-table-thead > tr > th {
      border-radius: 0 !important;
      color: #666666 !important;
      background: #fafafa !important;
      border-right: 1px solid #f0f0f0 !important;
      border-bottom: 1px solid #f0f0f0 !important;

      &:last-child {
        border-right: none !important;
      }
    }

    // 表格内容样式
    .ant-table-tbody {
      > tr {
        > td {
          color: #666666;
          border-right: 1px solid #f0f0f0;
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-right: none;
          }
        }

        &:last-child > td {
          border-bottom: 1px solid #f0f0f0;
        }

        &:hover > td {
          background: #fafafa !important;
        }
      }
    }

    // 确保链接按钮的颜色不受影响
    .ant-btn-link {
      color: #1890ff;

      &[danger] {
        color: #ff4d4f;
      }
    }

    // 分页区域样式
    .ant-table-pagination {
      margin: 16px 0;
      border-top: 1px solid #f0f0f0;
      padding-top: 16px;
    }

    // 添加选中行的样式
    .ant-table-row-selected > td {
      background-color: #e6f7ff !important;
    }

    // 选中行悬停样式
    .ant-table-row-selected:hover > td {
      background-color: #e6f7ff !important;
    }
  }

  // 确保两个表格样式一致
  .dict-sub {
    :deep(.ant-table-wrapper) {
      .ant-table {
        border: 1px solid #f0f0f0;
      }
    }
  }
</style>
